﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

using iTextSharp.text;
using iTextSharp.text.pdf;

namespace iPdf
{
    class PdfDecryptor: SinglePdfManipulator<DecryptOption>
    {
        public string Password
        {
            get
            {
                return pageOption.OwnerPassword;
            }
        }


        protected bool IsPasswordSecurity
        {
            get
            {
                return pageOption.SecurityLevelId == SecurityLevelId.PasswordSecurity;
            }
        }

        protected override void ReadPdf(string fileName)
        {
            if (IsPasswordSecurity)
            {
                if (!string.IsNullOrEmpty(Password))
                {
                    reader = new PdfReader(fileName, DocWriter.GetISOBytes(Password));
                }
                else
                {
                    reader = new PdfReader(fileName);
                }
            }
            else
            {
                reader = new PdfReader(fileName, pageOption.Certificate.GetCertificates()[0], pageOption.Certificate.PrivateKey);
            }
        }

        protected override void Manipulate()
        {
            if (pageOption.ChangePermissions)
            {
                int permissions = pageOption.Permission.Permissions;
                if (IsPasswordSecurity)
                {
                    byte[] userPassword = pageOption.KeepOpenPassword ?
                        reader.ComputeUserPassword() : null;
                    byte[] ownerPassword = DocWriter.GetISOBytes(pageOption.OwnerPassword);

                    stamper.SetEncryption(userPassword, ownerPassword,
                        permissions, PdfWriter.STRENGTH128BITS);
                }
                else
                {
                    stamper.SetEncryption(pageOption.Certificate.GetCertificates(),
                                                new int[] { permissions },
                                                PdfWriter.STANDARD_ENCRYPTION_128);
                }
            }
        }

    }
}
